package com.xyzk.diagnose.activity.other;


import java.util.ArrayList;
import java.util.List;

import com.xyzk.diagnose.R;
import com.xyzk.diagnose.activity.adapter.SettingAdapter;
import com.xyzk.diagnose.activity.adapter.SettingMenuAdapter;
import com.xyzk.diagnose.activity.adapter.SettingQueryAdapter;
import com.xyzk.diagnose.entity.Cartype;
import com.xyzk.diagnose.tools.Common;
import com.xyzk.diagnose.tools.Commonfunc;
import com.xyzk.diagnose.tools.DbAdapter.TableMain;
import com.xyzk.diagnose.view.CToast;
import com.xyzk.diagnose.view.dialog.CPopupWindow;
import com.xyzk.diagnose.view.dialog.InputDialog;
import com.xyzk.diagnose.view.dialog.LoginDialog;
import com.xyzk.diagnose.view.dialog.ShowDialog;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

public class SettingActivity extends Activity implements OnClickListener{

	private Activity activity = this;
	private LinearLayout llQueryData, llFeedBack, llInternet,ll_selectmodule;
	//左边菜单栏列表  打印机序号列表   查询数据列表
	private ListView lvMenu, lvSelect, lvData;
	private EditText etContent, etContact, etStartDate, etEndDate, etVin;
	private CheckedTextView ctvInternet;
	private String result = "全部", station = "全部";
	private Button btnQuery, btnUpload;
	private TextView  tvShow, tvResult, tvStation;
	private SettingQueryThread thread;
	private SettingMenuAdapter menuAdapter;
	private SettingAdapter selectAdapter;
	private ArrayList<String> selectDatas = new ArrayList<String>();
	private ArrayList<String> printDatas  = new ArrayList<String>();
	private ArrayList<String> stationDatas = new ArrayList<String>();
	private ArrayList<String> resultDatas = new ArrayList<String>();
	private CPopupWindow popWin;
	private boolean isPrint = true;
	private boolean uploadOne = true;//是否上传单条数据
	private boolean isShow;
	private Spinner m_select_spinner = null;
	private Spinner m_selectCan_spinner = null;
	private ArrayList<String> m_selectCan_spinnerarray = new ArrayList<String>();
	private ArrayList<String> m_select_spinnerarray = null;
	private ArrayAdapter<String> m_select_spinneradapter = null;
	private ArrayAdapter<String> m_selectCan_spinneradapter = null;

	//处理查询结果
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
				case Common.UPLOAD_DATA:
					if(isShow){
						showQueryData();
					}
					break;
				case Common.UPLOAD_DATA_NULL:
					CToast.show("没有查到相关数据");
					showQueryData();
					break;
				case Common.UPLOAD_DATA_FAILED:
					CToast.show("上传失败");
					break;
				case Common.UPLOAD_DATA_AGO:
					CToast.show("数据已经上传过");
					break;
				case Common.UPLOAD_DATA_SUCCESS:
					if(uploadOne){//上传单条数据
						CToast.show("上传成功");
					}else{//上传所有数据
						if(thread.uploading == thread.uplist.size() - 1){
							CToast.show("上传完成");
						}else{
							CToast.show("正在上传...");
						}
					}
					break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setting);
		initViews();
		setAdapter();
		setListener();
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		//从缓存获取can连接设置
		SharedPreferences settings = getSharedPreferences("Eol_KF", Context.MODE_PRIVATE);
		//3.生成一个保存编辑变量
		int  Communication= settings.getInt("Communication",0);
		m_selectCan_spinner.setSelection(Communication, true);
		m_selectCan_spinneradapter.notifyDataSetChanged();
		int printNum = settings.getInt("printNum",1);//默认打印机1
		selectAdapter.setSelected(printNum-1);
		selectAdapter.notifyDataSetChanged();

	}

	/**
	 * 初始化控件
	 */
	private void initViews(){
		lvMenu = (ListView) findViewById(R.id.lv_select_menu);
		lvSelect = (ListView) findViewById(R.id.lv_dialog_select);
		llQueryData = (LinearLayout) findViewById(R.id.ll_querydata);
		llInternet =(LinearLayout) findViewById(R.id.ll_settingActivity_internet);
		llFeedBack =(LinearLayout) findViewById(R.id.ll_feedback);
		ll_selectmodule = (LinearLayout)findViewById(R.id.ll_selectmodule);

		//意见反馈
		btnQuery = (Button) findViewById(R.id.btn_feedback_send);
		etContact = (EditText) findViewById(R.id.et_feedback_phone);
		etContent = (EditText) findViewById(R.id.et_feedback_content);
		ctvInternet = (CheckedTextView) findViewById(R.id.ctv_settingActivity_internet);
		ctvInternet.setChecked("1".equals(Commonfunc.getSharedPreference(Common.INTERNET, "0")));
//
//		ctvCan = (CheckedTextView) findViewById(R.id.ctv_settingActivity_can);
//		ctvCan.setChecked("1".equals(Commonfunc.getSharedPreference(Common.CAN, "0")));
		//上传MES数据
		lvData = (ListView) findViewById(R.id.lv_query_data);
		btnQuery = (Button) findViewById(R.id.btn_data_query);
		btnUpload = (Button) findViewById(R.id.btn_data_upload);
		etStartDate = (EditText) findViewById(R.id.et_start_date);
		etEndDate = (EditText) findViewById(R.id.et_end_date);
		etVin = (EditText) findViewById(R.id.et_vin_query);
		tvShow = (TextView) findViewById(R.id.tv_querydata_textview);
		tvResult = (TextView) findViewById(R.id.tv_result);
		tvStation = (TextView) findViewById(R.id.tv_station);

		btnQuery.setOnClickListener(this);
		btnUpload.setOnClickListener(this);
		ctvInternet.setOnClickListener(this);
//		ctvCan.setOnClickListener(this);
		tvResult.setOnClickListener(this);
		tvStation.setOnClickListener(this);

		thread = new SettingQueryThread();
		thread.setHandler(handler);

		//初始化车型选择
		m_select_spinner = (Spinner)findViewById(R.id.et_selectmodule_spinner);
		m_select_spinnerarray = GetCarList();
		//load车型

		m_select_spinneradapter = new ArrayAdapter<String>(this, R.layout.my_spinner_select_item ,m_select_spinnerarray);
		m_select_spinneradapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		m_select_spinner.setAdapter(m_select_spinneradapter);
		m_select_spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				// TODO Auto-generated method stub

			}
		});
		m_selectCan_spinner = (Spinner)findViewById(R.id.et_selectCan_spinner);
		m_selectCan_spinnerarray.add("蓝牙连接");
		m_selectCan_spinnerarray.add("有线连接");
		//load车型

		m_selectCan_spinneradapter = new ArrayAdapter<String>(this, R.layout.my_spinner_selectcan_item ,m_selectCan_spinnerarray);
		m_selectCan_spinneradapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		m_selectCan_spinner.setAdapter(m_selectCan_spinneradapter);
		m_selectCan_spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				Common.Communication=position;
				// 存入缓存
				SharedPreferences settings = activity.getSharedPreferences("Eol_KF", Context.MODE_PRIVATE);
				//3.生成一个保存编辑变量
				SharedPreferences.Editor editor = settings.edit();
				editor.putInt("Communication",position);
				//步骤4：提交
				editor.commit();
			}
		});
	}
	private ArrayList<String> GetCarList(){
		List<String> filelist = Commonfunc.GetDictionarySonList(Common.GUEST);
		if(filelist == null) return null;
		ArrayList<String> list = new ArrayList<String>();
		for(int i = 0; i < filelist.size(); i ++){
			list.add(filelist.get(i));
		}
		return list;
	}

	/**
	 * ListView处理item点击事件
	 */
	private void setListener(){
		//主菜单点击事件处理
		lvMenu.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
									int position, long id) {
				showPage(position);
			}
		});
		//打印机选择点击事件处理
		lvSelect.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
									int position, long id) {
				if(isPrint){//选择打印机序号
					Common.printNum = position + 1;
					// 将打印机存入缓存
					SharedPreferences settings = activity.getSharedPreferences("Eol_KF", Context.MODE_PRIVATE);
					//3.生成一个保存编辑变量
					SharedPreferences.Editor editor = settings.edit();
					editor.putInt("printNum",position+1);
					//步骤4：提交
					editor.commit();
				}else{//固定工位选择
					Commonfunc.setSharedPreference(Common.STATION, position + "");
				}
				selectAdapter.setSelected(position);
				selectAdapter.notifyDataSetChanged();
			}
		});
		//查询数据点击事件处理
		lvData.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
									final int position, long id) {
				uploadOne = true;
				final ShowDialog dialog = new ShowDialog(SettingActivity.this);
				dialog.setText("确认上传数据吗?");
				dialog.showCancelButton();
				dialog.onClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						thread.new UploadThread(position).start();
						dialog.dismiss();
					}
				});
			}
		});
	}

	/**
	 * 设置左侧菜单数据源
	 */
	private void setAdapter(){
		String [] menus = {
				getString(R.string.SettingActivity_print_number),
				getString(R.string.SettingActivity_select_station),
				getString(R.string.SettingActivity_query_datas),
				getString(R.string.SettingActivity_print_data),
				getString(R.string.SettingActivity_internet),
				getString(R.string.SettingActiivity_selectcar),
				getString(R.string.SettingActivity_feedback)};
		int [] resIds={R.drawable.setting_print_num,R.drawable.setting_station,R.drawable.setting_data,
				R.drawable.setting_print_result, R.drawable.setting_internet,R.drawable.setting_selectmodule,R.drawable.setting_feedback};

		menuAdapter = new SettingMenuAdapter(menus, resIds);
		lvMenu.setAdapter(menuAdapter);

		for (int i = 1; i < 6; i++) {
			printDatas.add(getString(R.string.SettingActivity_print) + " " + i);
		}

		selectDatas.addAll(printDatas);
		selectAdapter = new SettingAdapter(selectDatas, R.layout.activity_setting_print_item);
		selectAdapter.setSelected(Common.printNum - 1);
		lvSelect.setAdapter(selectAdapter);

		ArrayList<String> station = Cartype.getInstance().getStationsList();

		resultDatas.add("全部");
		resultDatas.add(Common.OK);
		resultDatas.add(Common.NG);

		stationDatas.add("全部");
		for(int i = 0; i < station.size(); i ++){
			stationDatas.add(station.get(i));
		}
	}


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.btn_data_query://查询数据
				isShow = true;
				queryData();
				break;
			case R.id.btn_data_upload://上传数据
				uploadOne = false;
				thread.new UploadThread(-1).start();
				break;
			case R.id.btn_feedback_send://提交意见
				if(TextUtils.isEmpty(etContent.getText().toString()) || TextUtils.isEmpty(etContact.getText().toString())){
					CToast.show(R.string.SettingActivity_feedback_content);
				}else{
					CToast.show(R.string.SettingActivity_feedback_success);
				}
			case R.id.ctv_settingActivity_internet://联网设置
				ctvInternet.setChecked(!ctvInternet.isChecked());
				Commonfunc.setSharedPreference(Common.INTERNET, !ctvInternet.isChecked() ? "0" : "1");
				break;
//			case R.id.ctv_settingActivity_can://CAN设置
//				ctvCan.setChecked(!ctvCan.isChecked());
//				Commonfunc.setSharedPreference(Common.CAN, !ctvCan.isChecked() ? "0" : "1");
//				break;
			case R.id.tv_result://查询结果筛选
				popWin = new CPopupWindow(this, resultDatas);
				popWin.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
				popWin.onClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
						result = resultDatas.get(arg2);
						tvResult.setText(resultDatas.get(arg2));
						popWin.dismiss();
					}
				});
				break;
			case R.id.tv_station://查询工位筛选
				popWin = new CPopupWindow(this, stationDatas);
				popWin.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
				popWin.onClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
						station = stationDatas.get(arg2);
						tvStation.setText(stationDatas.get(arg2));
						popWin.dismiss();
					}
				});
		}
	}

	/**
	 * 按选择条件查询
	 */
	private void queryData(){
		String where = "";
		ArrayList<String> whereArg = new ArrayList<String>();
		int num = 0;
		//vin码
		String vin = etVin.getText().toString();
		if(vin.length() == 17){
			where += TableMain.vin + "=?";
			whereArg.add(vin);
			num ++;
		}
		//结果
		if(!"全部".equals(result)){
			if(num != 0){
				where += " and ";
			}
			where += TableMain.result + "=?";
			whereArg.add(result);
			num ++;
		}
		//工位
		if(!"全部".equals(station)){
			if(num != 0){
				where += " and ";
			}
			where += TableMain.carstation + "=?";
			whereArg.add(station);
			num ++;
		}
		//日期
		String startDate = etStartDate.getText().toString();
		String endDate = etEndDate.getText().toString();
		if(startDate.length() == 15 && endDate.length() == 15){//转换日期标准格式
			startDate = startDate.substring(0,4) + "-" + startDate.substring(4,6) + "-" +
					startDate.substring(6,11) + ":" + startDate.substring(11,13) + ":" + startDate.substring(13,15);
			endDate = endDate.substring(0,4) + "-" + endDate.substring(4,6) + "-" +
					endDate.substring(6,11) + ":" + endDate.substring(11,13) + ":" + endDate.substring(13,15);
			if(num != 0){
				where += " and ";
			}
			where += TableMain.timestart +  " between " + "'" + startDate + "'" + " and " + "'" + endDate + "'";
		}else if(startDate.length() == 0 && endDate.length() == 0){//都没输入也可以
			//不需要处理
		}else{
			CToast.show(R.string.SettingActivity_date_error);
			return;
		}
		String [] arg = new String[whereArg.size()];
		whereArg.toArray(arg);

		thread.isShow = true;
		thread.new SQLiteThread(where, arg).start();
	}

	/**
	 * 显示查询数据
	 */
	public void showQueryData(){
		if(thread.uplist == null){
			tvShow.setVisibility(View.VISIBLE);
			tvShow.setText("未查询到数据");
			lvData.setVisibility(View.GONE);
		}else{
			tvShow.setVisibility(View.GONE);
			lvData.setVisibility(View.VISIBLE);
			SettingQueryAdapter adapter = new SettingQueryAdapter(this, thread.uplist);
			lvData.setAdapter(adapter);
		}
	}

	/*
	 * 显示界面
	 * @param pos
	 */
	private void showPage(int pos){
		menuAdapter.setSelected(pos);
		menuAdapter.notifyDataSetChanged();
		if(pos == 0 || pos == 1){//选择打印机
			selectDatas.clear();;
			if(pos == 0){
				isPrint = true;
				selectDatas.addAll(printDatas);
				selectAdapter.setSelected(Common.printNum - 1);
				selectAdapter.notifyDataSetChanged();
				lvSelect.setVisibility(View.VISIBLE);
				llQueryData.setVisibility(View.GONE);
				llFeedBack.setVisibility(View.GONE);
				llInternet.setVisibility(View.GONE);
				ll_selectmodule.setVisibility(View.GONE);
			}
			else if(pos == 1)
			{
				//OnloginDialog();
				isPrint = false;
				selectDatas.addAll(stationDatas);
				selectAdapter.setSelected(Integer.valueOf(Commonfunc.getSharedPreference(Common.STATION)));
				selectAdapter.notifyDataSetChanged();
				lvSelect.setVisibility(View.VISIBLE);
				llQueryData.setVisibility(View.GONE);
				llFeedBack.setVisibility(View.GONE);
				llInternet.setVisibility(View.GONE);
				ll_selectmodule.setVisibility(View.GONE);
			}

		}else if(pos == 2){//上传MES数据
			lvSelect.setVisibility(View.GONE);
			llQueryData.setVisibility(View.VISIBLE);
			llFeedBack.setVisibility(View.GONE);
			llInternet.setVisibility(View.GONE);
			ll_selectmodule.setVisibility(View.GONE);
		}else if(pos == 3){//重新打印结果
			queryForVin();//查询数据并打印
			lvSelect.setVisibility(View.GONE);
			llQueryData.setVisibility(View.GONE);
			llFeedBack.setVisibility(View.GONE);
			llInternet.setVisibility(View.GONE);
			ll_selectmodule.setVisibility(View.GONE);
		}else if(pos == 4){//联网设置
			lvSelect.setVisibility(View.GONE);
			llQueryData.setVisibility(View.GONE);
			llFeedBack.setVisibility(View.GONE);
			llInternet.setVisibility(View.VISIBLE);
			ll_selectmodule.setVisibility(View.GONE);
		}else if(pos == 5) //车型配置
		{
			lvSelect.setVisibility(View.GONE);
			llQueryData.setVisibility(View.GONE);
			llFeedBack.setVisibility(View.GONE);
			llInternet.setVisibility(View.GONE);
			ll_selectmodule.setVisibility(View.VISIBLE);
		}
		else if(pos == 6){//意见反馈
			lvSelect.setVisibility(View.GONE);
			llQueryData.setVisibility(View.GONE);
			llFeedBack.setVisibility(View.VISIBLE);
			llInternet.setVisibility(View.GONE);
			ll_selectmodule.setVisibility(View.GONE);
		}
	}
	private void OnloginDialog()
	{
		final LoginDialog logDialog = new LoginDialog(this);
		logDialog.setOnOKButton(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String user = logDialog.GetNameString();
				String password = logDialog.GetPasswordString();
				if(user.equals("admin") && password.equals("kaifeng"))
				{
					logDialog.dismiss();
					isPrint = false;
					selectDatas.addAll(stationDatas);
					selectAdapter.setSelected(Integer.valueOf(Commonfunc.getSharedPreference(Common.STATION)));
					selectAdapter.notifyDataSetChanged();
					lvSelect.setVisibility(View.VISIBLE);
					llQueryData.setVisibility(View.GONE);
					llFeedBack.setVisibility(View.GONE);
					llInternet.setVisibility(View.GONE);
					ll_selectmodule.setVisibility(View.GONE);
				}
			}
		});
		logDialog.show();
		return;
	}
	/**
	 * VIN查询
	 * @param isShow 只显示查询数据
	 */
	private void queryForVin(){
		final InputDialog dialog = new InputDialog(this);
		dialog.setTitle(R.string.Dialog_input_vin);
		//		dialog.setEditString("LJ8F7C5H2FB910121");
		dialog.onClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				final String vin = dialog.getEditString();
				if(!Commonfunc.checkVinFormat(vin.getBytes())){
					CToast.show(R.string.Mainactivity_input_vin);
					dialog.setEditString("");
					dialog.setHintText(R.string.Dialog_input_vin);
					return;
				}else{
					isShow = false;
					thread.new SQLiteThread(TableMain.vin + "=?", new String[]{vin}).start();
					Commonfunc.sleep(Common.DIALOG_WAIT_TIME);
					if(thread.uplist != null){
						thread.new UploadThread(thread.uplist.size() - 1).start();
					}
					dialog.dismiss();
				}
			}
		});
		dialog.show();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if(popWin != null){
				popWin.dismiss();
				popWin = null;
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}
}
